import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import api from '../../services/api';

// 异步thunk
export const fetchReports = createAsyncThunk(
  'reports/fetchReports',
  async (_, { rejectWithValue }) => {
    try {
      const response = await api.get('/reports/summary');
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '获取报表失败');
    }
  }
);

export const fetchRevenueReport = createAsyncThunk(
  'reports/fetchRevenueReport',
  async ({ start_date, end_date }, { rejectWithValue }) => {
    try {
      const response = await api.get('/reports/revenue', {
        params: { start_date, end_date }
      });
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '获取收入报表失败');
    }
  }
);

export const fetchFlightOccupancyReport = createAsyncThunk(
  'reports/fetchFlightOccupancyReport',
  async (_, { rejectWithValue }) => {
    try {
      const response = await api.get('/reports/flight-occupancy');
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '获取航班载客率报表失败');
    }
  }
);

// 初始状态
const initialState = {
  reports: {
    totalRevenue: 0,
    totalBookings: 0,
    totalFlights: 0,
    totalPassengers: 0,
    revenueByMonth: [],
    flightOccupancy: [],
    bookingStatusDistribution: [],
    topRoutes: [],
  },
  loading: false,
  error: null,
};

// Slice定义
const reportSlice = createSlice({
  name: 'reports',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      // fetchReports
      .addCase(fetchReports.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchReports.fulfilled, (state, action) => {
        state.loading = false;
        state.reports = { ...state.reports, ...action.payload };
      })
      .addCase(fetchReports.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // fetchRevenueReport
      .addCase(fetchRevenueReport.fulfilled, (state, action) => {
        state.reports.revenueByMonth = action.payload.revenueByMonth;
      })
      // fetchFlightOccupancyReport
      .addCase(fetchFlightOccupancyReport.fulfilled, (state, action) => {
        state.reports.flightOccupancy = action.payload.flightOccupancy;
      });
  },
});

export const { clearError } = reportSlice.actions;
export default reportSlice.reducer;